package com.chinaedu.oc.util.csv;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.activemq.protobuf.compiler.FieldDescriptor;

import com.chinaedu.oc.util.common.StringUtil;

public class CsvCreater <T>{
	
	/**
	 * 生成scv文件工具类
	 * @Description: TODO
	 * @param @param listData 数据
	 * @param @param fields 需要导出的字段名称,这些字段只能来源于本类以及父类！！！
	 * @param @param head 表头（跟字段对应）
	 * @param @param fileName 生成的文件名称
	 * @param @param response HttpServletResponse
	 * @param @throws DataCheckException 表头和字段不一致异常
	 * @param @throws DataNullException  数据为空异常
	 * @return void    返回类型 
	 * @throws
	 */
	public void createCsv(List<T> listData,String[] fields, String[] head, String fileName,  HttpServletResponse response){
		
		ExportUtil rt = new ExportUtil();
		
		if(listData != null && listData.size() >= 1) {
			
			List<String> selfFields = new ArrayList<>();
			List<String> parentFields = new ArrayList<>();
			Field[] ffff = listData.get(0).getClass().getDeclaredFields();
			for(Field f : ffff) {
				selfFields.add(f.getName());
			}
			ffff = listData.get(0).getClass().getSuperclass().getDeclaredFields();
			for(Field f : ffff) {
				parentFields.add(f.getName());
			}
			
			if(head==null || fields == null || head.length != fields.length) {
				throw new RuntimeException("表头信息错误");
			}
			
			File file = new File("/"+System.currentTimeMillis()+".csv");
			
			PrintWriter pw = null;
			try {
				pw = new PrintWriter(file);
				//写入表头
				pw.println(rt.toStr(head));
				try {
					for(T t : listData) {
						
//						Field[] fs = new Field[fields.length];
//						for(int i=0; i<fs.length; i++) {
//							fs[i] = t.getClass().getDeclaredField(fields[i]);
//						}
						String[] strs = new String[fields.length];
						for(int i=0; i<fields.length; i++) {
							Method m = null;
							if(selfFields.contains(fields[i])) {
								m = t.getClass().getMethod("get"+StringUtil.firstToUp(fields[i]));
								
							}else {
								m = t.getClass().getSuperclass().getMethod("get"+StringUtil.firstToUp(fields[i]));
							}
							String str = rt.dealValue(m.invoke(t));
							strs [i] = str;
							
						}
						pw.println(rt.toStr(strs));
					}
				} catch (SecurityException e2) {
					e2.printStackTrace();
				} catch (NoSuchMethodException e2) {
					e2.printStackTrace();
				} catch (IllegalAccessException e2) {
					e2.printStackTrace();
				} catch (IllegalArgumentException e2) {
					e2.printStackTrace();
				} catch (InvocationTargetException e2) {
					e2.printStackTrace();
				}
				pw.flush();
				
				//输入流，开始读流输出文件
				FileInputStream fis = new FileInputStream(file);
				
				
				response.setContentType("application/ms-txt.numberformat:@");
				response.setCharacterEncoding("UTF-8");
				response.setHeader("Pragma", "public");
				response.setHeader("Cache-Control", "max-age=30");
				try {
					response.setHeader("Content-Disposition", "attachment; filename=" + new String((fileName+".csv").getBytes("utf-8"),"iso-8859-1"));
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
				
				try {
					ServletOutputStream os = response.getOutputStream();
					int len = 0;
					byte[] b = new byte[100];
					while((len = fis.read(b)) != -1) {
						os.write(b, 0, len);
					}
					
					os.flush();
					
					os.close();
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				if(pw != null) {
					pw.close();
				}
			}
			//System.out.println(file.getAbsolutePath());
			boolean bool = file.delete();
			//System.out.println("删除文件："+bool);
		}else {
			throw new RuntimeException("数据为空");
		}
	}
	
	
}
